'use strict';
let reg = /^\[CQ:at,qq=1544392599] 语音(.*?)$/;
const fs = require('fs');
const googleTTS = require('google-tts-api');
var exec = require('child_process').exec;
const Service = require('egg').Service;

class AudioService extends Service {
  async regular(res) {
    let str = res.message;
    return reg.test(str);
  }

  async getMp3(str) {
    googleTTS
      .getAudioBase64(`${str}`, {
        lang: 'zh-TW'
      })
      .then((base64) => {
        const buffer = Buffer.from(base64, 'base64');
        fs.writeFileSync('../public/test.mp3', buffer, {
          encoding: 'base64'
        });
      })
      .catch(console.error);
  }

  async mp3ToAmr() {
    return new Promise(function (reslove, reject) {
      try {
        exec('ffmpeg -i ../public/test.mp3 -ar 8000 -ac 1 ../public/test.amr');
        reslove("成功生成amr")
      } catch (error) {
        reject(error)
      }
    })
  }

  async sendAudio(res) {
    let sendMsg = this.ctx.service.sendMsg;
    let msg = res.message.match(reg);
    msg = msg[1];
    try {
      await getMp3(msg);
      await mp3ToAmr();
      await sendMsg.sendToGroup({
        id: res.group_id,
        msg: '[CQ:record,file=file://127.0.0.1/C:/Users/Administrator/Downloads/123.amr]'
      })
    } catch (error) {
      sendMsg.sendToGroup({
        id: res.group_id,
        msg: `生成失败`
      })
    }
  }
}

module.exports = AudioService;